package com.iogogogo.supervisord4j.util.parser;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Objects;

/**
 * Created by tao.zeng on 2022/1/18.
 */
@Slf4j
public class LocalDateTimeParser implements TimestampParser {

    private final String value;

    public LocalDateTimeParser(String value) {
        this.value = value;
    }

    @Override
    public LocalDateTime parse(List<DateTimeFormatter> pattern) {
        DateTimeParseException lastException = null;
        LocalDateTime dateTime = null;
        try {
            dateTime = LocalDateTime.parse(value);
        } catch (DateTimeParseException e) {
            lastException = e;
            for (DateTimeFormatter formatter : pattern) {
                try {
                    dateTime = LocalDateTime.parse(value, formatter);
                    log.info("match formatter:{}", formatter);
                    break;
                } catch (DateTimeParseException ex) {
                    ex.addSuppressed(e);
                    lastException = ex;
                }
            }
        }

        if (Objects.nonNull(dateTime)) return dateTime;

        throw lastException;
    }
}
